<template>
  <div class="report-item-container">
<!-- 顶部操作栏 -->
<div class="operation-bar">
  <!-- 添加报备项按钮 -->
  <el-button type="primary" @click="handleAddData" icon="Plus">添加报备项</el-button>
  <!-- 学期选择 -->
  <el-select v-model="head_filterForm.term" placeholder="请选择学期" clearable style="width: 150px;">
    <el-option
      v-for="term in terms"
      :key="term"
      :value="term"
      :label="term"
    />
  </el-select>
  <!-- 报备项目名 -->
  <el-select v-model="head_filterForm.report_name" placeholder="请选择报备项目" clearable style="width: 180px;">
    <el-option
      v-for="report_name in report_names"
      :key="report_name"
      :value="report_name"
      :label="report_name"
    />
  </el-select>
  <!-- 查询按钮 -->
  <el-button type="primary" @click="handleFilter" icon="Search">查询</el-button>
</div>

    <!-- 报备项表格 -->
    <el-card shadow="hover" class="table-card">
      <el-table
          :data="tableData"
          border
          style="width: 100%"
          v-loading="table_loading"
          stripe
          size="medium"
          highlight-current-row
      >
        <el-table-column prop="id" label="ID" width="80" align="center"/>

        <el-table-column prop="report_field" label="报备类型" min-width="200">
          <template #default="{ row }">
            <div>学期: {{ row.term }}</div>
            <div>报备项目: {{ row.report_name }}</div>
          </template>
        </el-table-column>

        <el-table-column prop="members" label="成员信息" min-width="250">
          <template #default="{ row }">
            <pre>{{ JSON.stringify(row.members, null, 2) }}</pre>
          </template>
        </el-table-column>
        <!--        报备信息-->
        <el-table-column prop="report_info" label="报备信息" min-width="200">
          <template #default="{ row }">
            <pre>{{ JSON.stringify(row.report_info, null, 2) }}</pre>
          </template>

        </el-table-column>

        <el-table-column label="附件" width="100" align="center">
          <template #default="scope">
          <a :href="scope.row.attachment" target="_blank">{{ scope.row.attachmentText || '附件' }}</a>
          </template>
        </el-table-column>

        <el-table-column prop="total_score" label="总分" width="100" align="center"/>
        <el-table-column prop="approval_status" label="审核状态" width="120" align="center"/>
        <el-table-column prop="scoring_status" label="评分状态" width="120" align="center"/>
        <el-table-column prop="explanation" label="评分解释" width="200"/>
        <el-table-column prop="created_at" label="创建时间" width="180"/>
        <el-table-column fixed="right" label="操作" width="180" align="center">
          <template #default="scope">
            <el-button
                type="danger"
                size="small"
                @click="handleClickDelete(scope.row)"
                :loading="delete_loading"
                icon="Delete"
                plain
            >
              删除
            </el-button>
            <el-button
                type="primary"
                size="small"
                @click="handleClickEdit(scope.row)"
                :loading="edit_loading"
                icon="Edit"
                plain
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <AddData ref="addDataRef" :tableType="tableType" :isAdmin="true" @refresh-table="refreshTable"/>
      <EditData ref="editDataRef" :tableType="tableType" :isAdmin="true" @refresh-table="refreshTable"/>
      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="filterForm.page"
            :page-size="10"
            layout="prev, pager, next, jumper, total"
            :total="total_datas"
            @current-change="handlePageChange"
            background
        />
      </div>
    </el-card>

  </div>
</template>

<script setup>
import {onMounted, reactive, ref, watch} from 'vue';
import {ElMessage} from "element-plus";

import {formDataApi, jsonApi} from "@/global.js";
import AddData from "@/components/Main/NewReportManagement/ReportItemPublic/AddData.vue";
import EditData from "@/components/Main/NewReportManagement/ReportItemPublic/EditData.vue";


const props = defineProps({
  tableType: {
    type: String,
    required: true
  }
});

// 状态管理
const tableData = ref([]);
const total_datas = ref(0);
const table_loading = ref(true);
const delete_loading = ref(false);
const edit_loading = ref(false);
//
// 筛选表单
const head_filterForm = reactive({
  term: '',
  report_name: '',
});

//建立一个本地浏览器变量localstorage存储report_fileds

const terms = ref([])
const report_names = ref([])
// 筛选表单
const filterForm = reactive({
  report_filed_id: '',
  approval_status: '',
  page: 1,
});


// 初始化数据
onMounted(() => {
  refreshTable();
  //设置默认学期
  getDefaultTerm();
  refreshReportFiled();

});

// 监听 term 变化
watch(
    () => head_filterForm.term,
    (newTerm) => {
      head_filterForm.report_name = '';
      if (newTerm) {
// 从 localStorage 获取并解析数据
        const reportFieldsStr = localStorage.getItem('report_fields');
        let report_fields = [];

        try {
          if (reportFieldsStr) {
            report_fields = JSON.parse(reportFieldsStr); // 将字符串转为对象/数组
          }
        } catch (e) {
          console.error("解析 report_fields 失败", e);
        }

// 筛选 term 匹配 newTerm 的项
        const matchedReports = report_fields.filter(item => String(item.term) === String(newTerm));

// 提取 report_name 填充到 report_names.value
        report_names.value = matchedReports.map(item => item.report_name);


      } else {
        // 如果 term 被清空，则清空 report_name 和下拉列表
        report_names.value = [];
        head_filterForm.report_name = '';
      }
    },
    {
      immediate: true // 立即执行一次
    }
);
// 刷新表格数据
const refreshTable = async () => {
  try {
    table_loading.value = true;
    let formData = new FormData();
    formData.append('term', head_filterForm.term);
    formData.append('report_name', head_filterForm.report_name);
    formData.append('approval_status', filterForm.approval_status);
    formData.append('page', filterForm.page);


    const response = await formDataApi('/newreport/item/get/', formData);

    if (!response.ok) {
      throw new Error(`API 请求失败: ${response.status}`);
    }

    const data = await response.json();

    // 确保数据结构正确
    if (data && data.datas && Array.isArray(data.datas)) {
      tableData.value = data.datas;
      total_datas.value = data.total_datas || 0;
    } else {
      throw new Error("API 返回的数据格式不正确");
    }
  } catch (error) {
    console.error("加载数据失败:", error);
    ElMessage.error(`数据加载失败: ${error.message}`);
    tableData.value = [];
    total_datas.value = 0;
  } finally {
    table_loading.value = false;
  }
};
//刷新报备信息
const refreshReportFiled = async () => {
  try {
    let formData = new FormData();
    formData.append('term', head_filterForm.term);

    const response = await formDataApi('/newreport/field/get/', formData);

    if (!response.ok) {
      throw new Error(`API 请求失败: ${response.status}`);
    }

    const data = await response.json();

    // 确保数据结构正确
    if (data && data.datas && Array.isArray(data.datas)) {
      localStorage.setItem('report_fields', JSON.stringify(data.datas));
      // 添加report_names
      // 提取唯一 report_name
      report_names.value = data.datas.map(item => item.report_name);

    } else {
      throw new Error("API 返回的数据格式不正确");
    }
  } catch (error) {
    console.error("加载数据失败:", error);
    ElMessage.error(`数据加载失败: ${error.message}`);
  } finally {
  }
}

//默认值设置
// 根据当前月份设置默认学期
const getDefaultTerm = () => {
  const now = new Date();
  const month = now.getMonth() + 1; // 月份从1开始
  const year = now.getFullYear();
  let this_term = ''

  // 8月-1月为秋季学期
  if (month >= 8 || month <= 1) {
    // 如果是1月，学年是上一年-当年
    if (month <= 1) {
      this_term = `${year - 1}-${year}学年秋季学期`;
    } else {
      this_term = `${year}-${year + 1}学年秋季学期`;
    }
  }
  // 2月-7月为春季学期
  else {
    this_term = `${year - 1}-${year}学年春季学期`;
  }
  head_filterForm.term = this_term

  //设置terms为往前推五年（10学期）
  const allTerms = [];
  for (let i = 0; i < 5; i++) {
    const fallTerm = `${year - i}-${year - i + 1}学年秋季学期`;
    const springTerm = `${year - i - 1}-${year - i}学年春季学期`;
    allTerms.unshift(fallTerm);
    allTerms.unshift(springTerm);
  }
  terms.value = allTerms;


};


// 事件处理
const handleFilter = () => {
  filterForm.page = 1; // 重置到第一页
  refreshTable();
};

const handlePageChange = (newPage) => {
  filterForm.page = newPage;
  refreshTable();
};

// 在父组件中
const addDataRef = ref(null);
const editDataRef = ref(null);

const handleAddData = () => {
  addDataRef.value.open();
};

const handleClickDelete = async (row) => {
  delete_loading.value = true;
  const response = await jsonApi('/newreport/item/delete/', JSON.stringify({id: row.id}))
  if (response.ok) {
    ElMessage.success('删除成功');
    await refreshTable();
  } else {
    ElMessage.error('删除失败');
  }
  delete_loading.value = false;
};

const handleClickEdit = (row) => {
  editDataRef.value.open(row);
};

const handleSucceedAdd = () => {
  refreshTable();
};

const handleSucceedEdit = () => {
  refreshTable();
};
</script>


<style scoped>
.report-item-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}



.filter-controls {
  display: flex;
  gap: 10px;
}

.table-card {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.members-container {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.el-table) {
  flex: 1;
}

:deep(.el-card__body) {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.operation-bar {
  margin-bottom: 20px;
}

.full-width {
  width: 100%;
}

.operation-bar {
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.filter-select,
.filter-btn {
  width: 100%;
}

/* 按钮统一高度，提升视觉一致性 */
.filter-select .el-input__inner,
.filter-btn .el-button {
  height: 40px;
  line-height: 40px;
}

/* 按钮悬停增强体验 */
.el-button--primary:hover {
  background-color: #3a7cae;
  transition: background-color 0.3s ease;
}

/* 响应式处理：在小屏幕上保持良好的排版 */
@media (max-width: 768px) {
  .operation-bar .el-col {
    margin-bottom: 10px;
  }
}.operation-bar {
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}


/* 按钮统一高度，提升视觉一致性 */
.filter-select .el-input__inner,
.filter-btn .el-button {
  height: 40px;
  line-height: 40px;
}
.operation-bar {
  display: flex;
  flex-wrap: wrap; /* 允许换行 */
  gap: 16px; /* 控件之间的间距 */
  align-items: center;
  padding: 16px 0;
}

.operation-bar .el-button--primary {
  white-space: nowrap;
}

.operation-bar .el-select {
  min-width: 120px;
}
</style>